<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useChatSimpleStore } from "@/stores/chatSimpleStore.js";
import { useAuthStore } from "@/stores/authStore.js";

const chatStore = useChatSimpleStore();
const authStore = useAuthStore();
const currentFriend = ref(null);
const inputMessage = ref('')
const messagesContainer = ref(null)

// 计算当前活跃聊天的消息
const currentMessages = computed(() => {
  if (!currentFriend.value) return [];
  return chatStore.privateChatMessage[currentFriend.value.friendId] || [];
});

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !currentFriend.value) return;

  // 创建本地消息对象
  const newMessage = {
    from: authStore.user.id,
    to: currentFriend.value.friendId,
    content: inputMessage.value,
    type: 'TEXT',
    timestamp: new Date().toISOString(),
    messageId: Date.now().toString(),
    sender: 'user'
  };

  // 添加到当前聊天记录
  if (!chatStore.privateChatMessage[currentFriend.value.friendId]) {
    chatStore.privateChatMessage[currentFriend.value.friendId] = [];
  }
  chatStore.privateChatMessage[currentFriend.value.friendId].push(newMessage);

  // 实际发送消息到后端
  chatStore.sendToUser(inputMessage.value, currentFriend.value.friendId);

  inputMessage.value = '';

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 选择好友
const selectFriend = (friend) => {
  currentFriend.value = friend;
  nextTick(() => {
    scrollToBottom();
  });
};

// 监听当前消息变化，自动滚动
watch(currentMessages, () => {
  nextTick(() => {
    scrollToBottom();
  });
}, { deep: true });

// 格式化时间
const formatTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toDateString() === today.toDateString()) {
    return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
  } else {
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
  }
};

// 获取显示名称（优先显示备注，没有备注显示昵称）
const getDisplayName = (friend) => {
  return friend?.nickname || friend?.remark || '未知用户';
};

// 状态文本转换
const getStatusText = (status) => {
  const statusMap = {
    'ONLINE': '在线',
    'OFFLINE': '离线',
    'BUSY': '忙碌',
    'AWAY': '离开'
  };
  return statusMap[status] || status;
};

// 组件挂载时连接并获取好友列表
onMounted(() => {
  chatStore.connect();
  chatStore.getFriendList();

  // 默认选中第一个好友（如果有）
  if (chatStore.friendList.length > 0) {
    currentFriend.value = chatStore.friendList[0];
  }

  scrollToBottom();
});
</script>

<template>
  <div class="chat-container">
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h2>聊天列表</h2>
      </div>
      <div class="chat-list">
        <div
            v-for="friend in chatStore.friendList"
            :key="friend.friendId"
            class="chat-item"
            :class="{ active: currentFriend?.friendId === friend.friendId }"
            @click="selectFriend(friend)"
        >
          <div class="chat-item-avatar">
            <img v-if="friend.avatar" :src="friend.avatar" :alt="getDisplayName(friend)">
            <div v-else class="avatar-placeholder">{{ getDisplayName(friend).charAt(0) }}</div>
          </div>
          <div class="chat-item-content">
            <div class="chat-item-name">{{ getDisplayName(friend) }}</div>
            <div class="chat-item-preview">
              <span class="status-badge" :class="friend.status.toLowerCase()">
                {{ getStatusText(friend.status) }}
              </span>
              {{ friend.lastMessage || '暂无消息' }}
            </div>
          </div>
          <div class="chat-item-time">{{ formatDateTime(friend.lastActive) }}</div>
        </div>

        <!-- 当没有好友时显示提示 -->
        <div v-if="chatStore.friendList.length === 0" class="no-friends">
          暂无好友
        </div>
      </div>
    </div>

    <div class="chat-main">
      <div v-if="currentFriend" class="chat-header">
        <div class="chat-header-info">
          <div class="chat-avatar">
            <img v-if="currentFriend.avatar" :src="currentFriend.avatar" :alt="getDisplayName(currentFriend)">
            <div v-else class="avatar-placeholder">{{ getDisplayName(currentFriend).charAt(0) }}</div>
          </div>
          <div>
            <h3>{{ getDisplayName(currentFriend) }}</h3>
            <p class="status">{{ getStatusText(currentFriend.status) }} - 最后活跃: {{ formatTime(currentFriend.lastActive) }}</p>
          </div>
        </div>
        <div class="chat-header-actions">
          <div class="remark-display" v-if="currentFriend.remark">
            备注：{{ currentFriend.remark }}
          </div>
        </div>
      </div>

      <!-- 当没有选中聊天时显示提示 -->
      <div v-else class="no-chat-selected">
        请选择一个聊天
      </div>

      <div v-if="currentFriend" class="chat-messages" ref="messagesContainer">
        <template v-if="currentMessages.length > 0">
          <div
              v-for="(message, index) in currentMessages"
              :key="message.messageId || index"
              class="message"
              :class="{ 'message-right': message.sender === 'user', 'message-left': message.sender !== 'user' }"
          >
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </template>
        <div v-else class="no-messages">
          暂无聊天记录
        </div>
      </div>

      <div v-if="currentFriend" class="chat-input">
        <div class="input-tools">
          <button class="icon-btn">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path
                  d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-5-9h10v2H7z"/>
            </svg>
          </button>
          <button class="icon-btn">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path
                  d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
            </svg>
          </button>
        </div>
        <textarea
            v-model="inputMessage"
            @keydown.enter.exact.prevent="sendMessage"
            placeholder="输入消息..."
            class="message-input"
            rows="1"
        ></textarea>
        <button class="send-btn" @click="sendMessage" :disabled="!inputMessage.trim()">
          <svg viewBox="0 0 24 24" width="20" height="20">
            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.no-friends, .no-chat-selected {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 14px;
}

.no-messages {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 14px;
}

.chat-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-sidebar {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f9f9f9;
}

.chat-item.active {
  background-color: #e9f5ff;
}

.chat-item-avatar {
  margin-right: 12px;
  position: relative;
}

.chat-item-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(45deg, #ff9a9e, #fad0c4);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.chat-item-content {
  flex: 1;
  min-width: 0;
}

.chat-item-name {
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-item-preview {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
}

.status-badge {
  font-size: 0.8rem;
  padding: 2px 6px;
  border-radius: 10px;
  margin-right: 6px;
  white-space: nowrap;
}

.status-badge.online {
  background: rgba(46, 204, 113, 0.2);
  color: #2ecc71;
}

.status-badge.offline {
  background: rgba(149, 165, 166, 0.2);
  color: #95a5a6;
}

.status-badge.busy {
  background: rgba(231, 76, 60, 0.2);
  color: #e74c3c;
}

.status-badge.away {
  background: rgba(241, 196, 15, 0.2);
  color: #f1c40f;
}

.chat-item-time {
  font-size: 12px;
  color: #999;
  align-self: flex-start;
  white-space: nowrap;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header-info {
  display: flex;
  align-items: center;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.chat-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
}

.status {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.chat-header-actions {
  display: flex;
  align-items: center;
}

.remark-display {
  background: rgba(0, 0, 0, 0.05);
  color: #666;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.9rem;
  white-space: nowrap;
}

.icon-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  color: #666;
  border-radius: 50%;
}

.icon-btn:hover {
  background-color: #f0f0f0;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 16px;
  display: flex;
  max-width: 80%;
}

.message-right {
  align-self: flex-end;
}

.message-left {
  align-self: flex-start;
}

.message-content {
  padding: 8px 12px;
  border-radius: 8px;
  position: relative;
}

.message-right .message-content {
  background-color: #007bff;
  color: white;
  border-bottom-right-radius: 0;
}

.message-left .message-content {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 0;
}

.message-text {
  word-wrap: break-word;
}

.message-time {
  font-size: 11px;
  margin-top: 4px;
  text-align: right;
}

.message-left .message-time {
  color: #999;
}

.message-right .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  background-color: #fff;
}

.input-tools {
  display: flex;
  margin-right: 8px;
}

.message-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
  resize: none;
  min-height: 40px;
  max-height: 120px;
  line-height: 1.5;
}

.message-input:focus {
  border-color: #007bff;
}

.send-btn {
  background-color: #007bff;
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-left: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover {
  background-color: #0069d9;
}

.send-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .chat-sidebar {
    width: 100%;
  }

  .chat-main {
    display: none;
  }

  .chat-item.active ~ .chat-main {
    display: flex;
  }
}
</style>